while 常見用法如下:
//while
count = 1
while count<=5:
print(count)
count += 1
// result
1
2
3
4
5
//while break
count = 1
while count != 6:
print(count)
count += 1
if count > 5:
break
//result
1
2
3
4
5
//while break continue
count = 0
while count != 6:
if count > 5:
break
count += 1
if count % 2 == 0:
continue
print(count)
//result
1
3
5
// while break continue & if else
guess_me = 7
number = 1
while True:
if number < guess_me:
print('too low')
elif number == guess_me:
print('found it!')
break
else:
print('oops')
break
number += 1
// result
too low
too low
too low
too low
too low
too low
found it!
guess_me = 7
for number in range(10):
if number < guess_me:
print('too low')
elif number == guess_me:
print('found it!')
break
else:
print('oops')
break
// result
too low
too low
too low
too low
too low
too low
too low
found it!
同樣的 guess_me = 7 for 會多顯示一次too low,其他常見for用法。
a =["A", "B", "C", "D", "E"]
for num in a:
print(num)
// result
A
B
C
D
E
for num in range(10,0,-1):
print(num)
// result
10
9
8
7
6
5
4
3
2
1
a = [0,9,2,2]
for num in a:
print(num)
// result
0
9
2
2
0 1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10
0 5 10 15 20 25